package postgres

import (
	"context"
	"quipus/internal/database/model"

	apb "quipus/proto/gen/assist"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
	"gorm.io/gorm/clause"
)

func (p *PGDB) UpsertKnotArrangement(ctx context.Context, upsert *model.KnotArrangement) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.KnotArrangement.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "knot_id"}, {Name: "related_knot_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"knot_id", "related_knot_id", "pinned"}),
	}).Create(upsert)
	if err != nil {
		return err
	}

	return nil
}

func (p *PGDB) ListKnotArrangement(ctx context.Context, find *apb.KnotArrangement) ([]*model.KnotArrangement, error) {
	p.query()
	qdo := q.WithContext(ctx)
	KnotArrangement := qdo.KnotArrangement
	if find.KnotId != 0 {
		KnotArrangement = KnotArrangement.Where(q.KnotArrangement.KnotID.Eq(find.KnotId))
	}

	if find.UserId != 0 {
		KnotArrangement = KnotArrangement.Where(q.KnotArrangement.UserID.Eq(find.UserId))
	}

	return KnotArrangement.Find()
}
